package com.copa.l2;

/**
 * @author copa
 * @createDate 2022-04-27 09:25
 * @function 递归法
 *

 */
public class Test2 {

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        int total = l1.val + l2.val;
        int next1 = total / 10;
        ListNode result = new ListNode(total % 10);
        // error: if (l1 != null || l2 != null || next1 != 0) {
        /**
         *  没判断好l1，l2，应该是 l1.next不为空 或者 l2.next不为空 或者 next1 不为0 才能进去， 而不是l1,l2
         *  java.lang.NullPointerException: Cannot read field "val" because "<local1>" is null
         *  at line 27, Solution.addTwoNumbers
         *  at line 29, Solution.addTwoNumbers
         *  at line 29, Solution.addTwoNumbers
         *  at line 54, __DriverSolution__.__helper__
         *  at line 87, __Driver__.main
         */
        if (l1.next != null || l2.next != null || next1 != 0) {
            // 优化写法(简洁些)，可以用三目运算符
            l1 = l1.next != null ? l1.next : new ListNode(0);
            l2 = l2.next != null ? l2.next : new ListNode(0);
            // 上面判断错了，下面这里就跟着错了 应该是 l1.next != null , l2.next != null
//            if (l1 != null) {
//                l1 = l1.next;
//            } else {
//                l1 = new ListNode(0);
//            }
//            if (l2 != null) {
//                l2 = l2.next;
//            } else {
//                l2 = new ListNode(0);
//            }
            l1.val += next1;
            result.next = addTwoNumbers(l1, l2);
        }
        // 按照思路，这个不应该写在外面，而要写在里面，详细分析看title.txt
        //result.next = addTwoNumbers(l1, l2);

        return result;
    }

    public static void main(String[] args) {
        ListNode l1 = new ListNode(2);
        l1.next = new ListNode(4);
        l1.next.next = new ListNode(3);
        ListNode l2 = new ListNode(5);
        l2.next = new ListNode(6);
        l2.next.next = new ListNode(4);
        ListNode listNode = new Test2().addTwoNumbers(l1, l2);
        while (listNode != null) {
            System.out.print(listNode.val + "\t");
            listNode = listNode.next;
        }
    }
}
